/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package au.com.domlogic.pvc.core.servlet;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 *
 * @author Domenic Figliomeni
 *
 * This wrapper adds a method to redirect a browser to a local resource in the same
 * way a servlet can forward a request response pair to a local resource.  This
 * saves the servlet developer from constructing a string representing the url of
 * a resource in the same context.  It depends on the URLCreator.
 */
public class LocalRedirectionResponseWrapper extends HttpServletResponseWrapper {

    public LocalRedirectionResponseWrapper(HttpServletResponse rs) {
        super(rs);
    }

    /**
     * Pass the request and local resource identifier to this method and the
     * browser will be redirected to the local resource.  If local resource
     * has a leading slash, then it will be dropped.  use 2 slashes "//" to
     * override this behaviour, though you shouldn't need to/
     * 
     * @param request
     * @param localResource
     * @throws IOException
     */
    public void sendLocalRedirect(HttpServletRequest request, String localResource)
            throws IOException {
        URLCreator urlCreator = new URLCreator();
        String baseUrl = urlCreator.getBaseUrlString(request);
        //get base url provides the trailing slash so if the local resource also does, then drop it
        if (localResource.charAt(0) == '/') {
            localResource = localResource.substring(1);
        }
        String url = baseUrl + localResource;
        this.sendRedirect(url);
    }
}
